<template>
  <div style="border: 1px solid #ccc; border-radius: 10px; overflow: hidden">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>

<script setup name="Editor">
import { upload } from "@/api/upload";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import hljs from "highlight.js";
import { ref } from "vue";
const proxy = getCurrentInstance();
const props = defineProps({
  value: {
    type: String,
    default: "",
  },
});
const mode = ref("default");
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref(props.value);
watch(
  () => props.value,
  (newVal) => {
    valueHtml.value = newVal;
  },
  { immediate: true }
);
// 模拟 ajax 异步获取内容
onMounted(() => {});

const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      maxFileSize: 5 * 1024 * 1024, // 5M

      // 自定义上传
      async customUpload(file, insertFn) {
        // 自己实现上传，并得到图片 url alt href
        let res = await uploadFile({ file, category: "editorImg" });
        if (res.code == 200) {
          // 最后插入图片
          insertFn(res.data.url);
        }
      },
    },

    uploadVideo: {
      maxFileSize: 5 * 1024 * 1024, // 5M
      // 自定义上传
      async customUpload(file, insertFn) {
        let res = await uploadFile({ file, category: "editorVideo" });
        if (res.code == 200) {
          insertFn(res.data.url);
        }
      },
    },
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const uploadFile = (data) => {
  return new Promise((resolve, reject) => {
    upload(data)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        proxy.$notify({
          title: "提交成功，刷新页面中...",
          type: "success",
        });
      });
  });
};
// 高亮处理函数
const highlightCode = (html) => {
  const tempDiv = document.createElement("div");
  tempDiv.innerHTML = html;
  const codeBlocks = tempDiv.querySelectorAll("pre code");

  codeBlocks.forEach((block) => {
    hljs.highlightBlock(block); // 高亮代码块
    block.classList.add("hljs"); // 确保样式生效
  });
};
const handleChange = (editor) => {
  // highlightCode(editor.getHtml());
};
const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

const getVal = () => {
  return editorRef.value.getHtml();
};
defineExpose({
  getVal,
});
</script>

<style lang="scss" scoped></style>
